#coding=utf-8
# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from message.functions import *
from member.functions import *
from library.functions import *
from django.contrib.auth.decorators import login_required
from message.models import *
from django.contrib.auth.models import User
from django.db.models import Q
from django.core.exceptions import *

@login_required
def index(request):
    message = 'hi, im user index!'
    return render_to_response('member/index.html', locals())

@login_required
def newMessage(request):
    next     = request.REQUEST.get('next', '/')
    if request.META['REQUEST_METHOD'] != 'POST':
        return render_to_response('message/new.html', locals())
    else:
        message_title   = request.POST.get('message_title', '')
        message_content = request.POST.get('message_content', '')
        sendto          = request.POST.get('sendto', '')
        
        try:
            toUser = User.objects.get(username__exact = sendto)
        except User.DoesNotExist, e:
            return showSystemMessage('没这人啊兄弟，没点错？', next)
        
        if is_baned_user(request.user, toUser):
            return showSystemMessage('对方拒绝你的消息', next)
        else:
            newMessage = Message(fromUser = request.user, toUser = toUser, title = message_title, content = message_content)
            newMessage.save()
        
            return showSystemMessage('发送消息成功', next)

@login_required    
def replyMessage(request, message_id):
    next     = request.REQUEST.get('next', '/')
    try:
        message = Message.objects.get(id__exact = message_id)
    except DoesNotExist, e:
        return showSystemMessage('没这消息啊兄弟，没点错？', next)
        
    if request.META['REQUEST_METHOD'] != 'POST':
        if request.user != message.fromUser and request.user != message.toUser:
            return showSystemMessage('你没这消息啊兄弟，没点错？', next)
        else:
            return render_to_response('message/reply.html', locals())
    else:
        message_title = request.POST.get('message_title', '')
        message_content = request.POST.get('message_content', '')
            
        if request.user != message.fromUser and request.user != message.toUser:
            return showSystemMessage('你没这消息啊兄弟，没点错？', next)
        elif is_baned_user(request.user, message.fromUser):
            return showSystemMessage('对方拒绝你的消息', next)
        else:
            replyMessage = Message(fromUser = request.user, toUser = message.fromUser, replyTo = message, title = message_title, content = message_content)
            replyMessage.save()
        
            return showSystemMessage('回复消息成功', next)

    
@login_required
def viewMessage(request, message_id):
    if request.META['REQUEST_METHOD'] != 'POST':
        next     = request.REQUEST.get('next', '/')
        return render_to_response('message/view.html', locals())
    else:
        account  = request.POST.get('account', '')
        password = request.POST.get('password', '')
        next     = request.REQUEST.get('next', '/')

        # 验证登陆是否正确
        login_user = authenticate(account = account, password = password)
        
        if login_user is not None and login_user.is_active:
            auth.login(request, login_user)
            
            # 回到上一页
            #if next != '':
            #    return HttpResponseRedirect(next)
            #return HttpResponseRedirect('/')
            return showSystemMessage("登陆成功,现在为您跳转...", next)
        else:
            return showSystemMessage("登陆失败, : (", next)

@login_required            
def listMessage(request):
    next     = request.REQUEST.get('next', request.path)
    
    #找到所有与登陆用户相关的消息树第一条
    root_messages = Message.objects.filter(Q(replyTo__isnull = True), Q(fromUser__exact = request.user) | Q(toUser__exact = request.user)).order_by('-createDate')
    
    messages_list = []
    
    #每个root_message是一个thread
    for message in root_messages:
        message_thread = message.message_set.all().order_by('createDate')
        tmp_list = [message]
        
        #如果有回复
        if message_thread:
            tmp_list += [m for m in message_thread]
        
        messages_list.append(tmp_list)
    
    return render_to_response('message/list.html', locals())

@login_required
def deleteMessage(request):
    next     = request.REQUEST.get('next', '/')
    if request.META['REQUEST_METHOD'] != 'POST':
        return  showSystemMessage('没事儿可做啊兄弟，没点错？', next)
    else:
        message_id = request.POST.get('message_id', '')
        
        try:
            message = Message.objects.get(id__exact = message_id)
        except DoesNotExist, e:
            return showSystemMessage('没这消息啊兄弟，没点错？', next)
            
        if request.user == message.fromUser:
            message.status = 'fromUserDelete'
        elif request.user == message.toUser:
            message.status = 'toUserDelete'
        else:
            return showSystemMessage('你没这消息啊兄弟，没点错？', next)
        
        return showSystemMessage('删除消息成功', next)

@login_required        
def renewMessage(request, message_id):
    pass